import router from './index'
import store from '../store'
import { message } from 'ant-design-vue'
import { getToken } from '../utils/cookie'

const LOGIN_PATH = '/login'

router.beforeEach(async (to, form, next) => {
  const isLoginPath: boolean = to.path === LOGIN_PATH

  const toLogin = () => next(LOGIN_PATH)

  if (getToken()) {
    if (isLoginPath) {
      next('/')
    } else {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      if (!Object.keys((store.state as any).user.userInfo).length) {
        await store.dispatch('user/refreshUser').then(() => next({ ...to, replace: true })).catch(() => {
          message.error('登录异常')
          toLogin()
        })
      } else {
        next()
      }
    }
  } else {
    if (isLoginPath) {
      next()
    } else {
      toLogin()
    }
  }
})
